package com.txm.qqview;

import com.txm.qqcommon.*;
import com.txm.service.ClientConnectServerThread;
import com.txm.service.UserClientService;

import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;

/**
 * 用户界面
 */
public class QQView {
    /**
     * 一级菜单的分隔符
     */
    private final String titleLine = "================";
    /**
     * 二级菜单的分隔符
     */
    private final String contentLine = "==========";

    public Scanner scanner = new Scanner(System.in);
    /**
     * 用户输入的操作指令
     */
    public char choice_char;
    /**
     * 登录后记录的用户名
     */
    public String userName;
    /**
     * 记录用户输入操作指令后，需要输入的内容
     */
    public String userInputCont = "";
    public User user_getter;

    public boolean isLive_thread = true;
    public boolean isLive_thread_ = true;
    public boolean printMenu = true;

    public ClientConnectServerThread ccst;
    public TransferFiles transferFiles;

    /**
     * 用于获取键盘输入的内容
     */
    private void printMenu(String title, String[] view, Scanner scanner, String titleLine) {
        //  打印页面，在用户选择完指令后，返回选择的指令并退出
        while (printMenu) {
            System.out.println(titleLine + title + titleLine);
            int i;
            ArrayList<Integer> arr = new ArrayList<Integer>();
            for (i = 0; i < view.length; i++) {
                if (view[i].equals("退出系统")) {
                    System.out.println("\t\t\t" + 9 + "、" + view[i]);
                    arr.add(9);
                    continue;
                }
                System.out.println("\t\t\t" + (i + 1) + "、" + view[i]);
                arr.add((i + 1));
            }
            System.out.println("请输入的选择：");
            String cont = scanner.next();
            if (cont.length() > 1) {
                System.out.println("请输入一位数字字符");
                continue;
            }
            char next = cont.charAt(0);
            try {
                if (arr.contains(Integer.parseInt(String.valueOf(next)))) {
                    //System.out.println("输入的值是在范围内，退出循环");
                    choice_char = next;
                    break;
                }
            } catch (Exception e) {
                System.out.println("输入有误，请重新输入。");
            }
        }
    }

    /**
     * 用户登录页面
     */
    public void getLoginView() {
        //获取登录页 面
        String[] loginView = new String[]{
                //登录页面
                "登录系统",
                "退出系统"
        };
        printMenu("欢迎登录网络通讯系统", loginView, scanner, titleLine);
    }

    public HashMap<String, String> getAccount() {
//      获取用户输入的账号
        HashMap<String, String> objectObjectHashMap = new HashMap<>();
        while (true) {
            try {
                System.out.print("请输入账号：");
                String username = scanner.next();
                if (username.isEmpty()) {
                    continue;
                }
                objectObjectHashMap.put("username", username);
                System.out.print("请输入密码：");
                String password = scanner.next();
                if (password.isEmpty()) {
                    continue;
                }
                objectObjectHashMap.put("password", password);
                break;
            } catch (Exception e) {
                System.out.println("getAccount Exception" + e);
            }
        }
        return objectObjectHashMap;
    }

    /**
     * 用户可操作的主菜单页面，当用户输入了操作指令后，会向服务器提交当前的指令
     */
    public void getMainView() {
        //获取主页
        String[] mainView = new String[]{
                "显示在线用户列表",
                "私发消息",
                "群发消息",
                "发送文件",
                "退出系统"
        };
        printMenu("网络通讯系统主页(" + userName + ")", mainView, scanner, contentLine);
        try {
            if (ccst.getSocket().isClosed()) return;
            if (choice_char == '1') {
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(ccst.getSocket().getOutputStream());
                objectOutputStream.writeObject(new Response("/getOnlineUsers", new Message("", "", "", "", MessageType.MESSAGE_GET_ONLINE_USER, null)));
                choice_char = '\u0000';
            }
            if (choice_char == '2') {
                String s = personChat("请输入你需要聊天的对象（用户ID）：");
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(ccst.getSocket().getOutputStream());
                objectOutputStream.writeObject(new Response("/personChat", new Message(userName, s, "开启一个聊天会话", "", MessageType.MESSAGE_SENDER_MSG_USER, null)));
                choice_char = '\u0000';
                userInputCont = "";
            }
            if (choice_char == '3') {
                String s = personChat("请输入房间号（群ID）：");
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(ccst.getSocket().getOutputStream());
                objectOutputStream.writeObject(new Response("/groupChat", new Message(ccst.user.getUserId(), null, s, "", MessageType.MESSAGE_SENDER_MSG_GROUP, null)));
                choice_char = '\u0000';
                userInputCont = "";
            }
            if (choice_char == '4') {
                String s = personChat("请输入你需要发送文件的对象（用户ID）：");
                choice_char = '\u0000';
                userInputCont = "";
                transferFiles = new TransferFiles(s, ccst);
            }
            if (choice_char == '9') {
                //线程结束，通知服务端端
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(ccst.getSocket().getOutputStream());
                Message message = new Message();
                message.setGetter(ccst.user.getUserId());
                message.setMsgType(MessageType.MESSAGE_SYSTEM_EXIT);
                message.setContent(ccst.user.getUsername() + "客户端退出。");
                message.setObject(ccst.user);
                objectOutputStream.writeObject(new Response("", message));
            }
        } catch (Exception e) {
            System.out.println("Exception: " + e);
        }
    }

    /**
     * 显示当前在线用户
     */
    public void viewOnlineUser(Message message) {
        System.out.println(contentLine + "当前在线用户（" + message.getSendTime() + "）" + contentLine);
        System.out.println(message.getContent());
        this.getMainView();
    }

    /**
     * 获取用户想要发送内容到的用户对象
     */
    public String personChat(String title) {
        while (true) {
            System.out.print(title);
            String next = scanner.next();
            try {
                Integer.parseInt(next);
            } catch (Exception e) {
                System.out.println("输入内容不合法");
                continue;
            }
            userInputCont = next;
            break;
        }
        return userInputCont;
    }

    /**
     * 呼出个人聊天页面（实现了同时监听用户输入，和读取消息功能）
     */
    public void personChatDetail(Message msg, Socket socket) {
        isLive_thread = true;
        isLive_thread_ = true;

        System.out.println(contentLine + "聊天页面（" + msg.getGetter() + "）" + contentLine);
        System.out.println(msg.getContent());

        Thread thread_scanner = new Thread(() -> {
            try {
                while (isLive_thread) {
                    System.out.println("发送消息（输入-1退出）：");
                    String next = scanner.next();
                    if (next.equals("-1")) {
                        break;
                    }
                    User user_getter = (User) msg.getObject();
                    ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
                    objectOutputStream.writeObject(new Response("/personChat", new Message(UserClientService.user.getUsername(), user_getter.getUsername(), next, "", MessageType.MESSAGE_CHAT_USER, user_getter)));
                    Thread.sleep(1000);
                }
//                System.out.println("thread_scanner exit");
                Message message = new Message();
                message.setSender(ccst.user.getUserId());
                message.setGetter(ccst.user.getUserId());
                message.setContent("退出聊天界面。");
                message.setMsgType(MessageType.MESSAGE_CHAT_USER_EXIT);
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
                objectOutputStream.writeObject(new Response("/personChat", message));
                this.getMainView();
            } catch (Exception e) {
                System.out.println("personChatDetail Exception" + e);
                e.printStackTrace();
            }
        });


        thread_scanner.start();


    }

    /**
     * 接收个人聊天消息
     */
    public void personChatBack(Message msg, Socket socket) {
        switch (msg.getMsgType()) {
            case MessageType.MESSAGE_CHAT_GROUP:
                System.out.println(contentLine + "来消息啦" + "房间：(" + msg.getGetter() + ")" + contentLine);
                System.out.println(msg.getSendTime() + " " + msg.getSender() + ":" + msg.getContent());
                break;
            case MessageType.MESSAGE_CHAT_GROUP_EXIT:
            case MessageType.MESSAGE_NOT_USER:
            case MessageType.MESSAGE:
                System.out.println(contentLine + "来消息啦" + contentLine);
                System.out.println(msg.getContent());
                this.getMainView();
                break;
            default:
                System.out.println(contentLine + "来消息啦" + contentLine);
                System.out.println(msg.getSendTime() + " " + msg.getContent());
                break;
        }

    }

    /**
     * 呼出个人聊天页面（实现了同时监听用户输入，和读取消息功能）
     */
    public void groupChatDetail(Message msg, Socket socket) {

        System.out.println(contentLine + "聊天页面（房间：" + msg.getContent() + "）" + contentLine);

        Thread thread_scanner = new Thread(() -> {
            try {
                while (true) {
                    System.out.println("发送消息（输入-1退出）：");
                    String next = scanner.next();
                    if (next.equals("-1")) {
                        break;
                    }

                    ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
                    objectOutputStream.writeObject(new Response("/groupChat", new Message(ccst.user.getUserId(), msg.getContent(), next, "", MessageType.MESSAGE_CHAT_GROUP, null)));
                    Thread.sleep(1000);
                }
//                System.out.println("thread_scanner exit");
                Message message = new Message();
                message.setSender(ccst.user.getUserId());
                message.setGetter(msg.getContent());
                message.setContent("退出群聊。");
                message.setMsgType(MessageType.MESSAGE_CHAT_GROUP_EXIT);
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
                objectOutputStream.writeObject(new Response("/groupChat", message));

            } catch (Exception e) {
                System.out.println("groupChatDetail Exception" + e);
                e.printStackTrace();
            }
        });


        thread_scanner.start();
    }

}
